//统计一个数字在排序数组中出现的次数。 
//
// 
//
// 示例 1: 
//
// 
//输入: nums = [5,7,7,8,8,10], target = 8
//输出: 2 
//
// 示例 2: 
//
// 
//输入: nums = [5,7,7,8,8,10], target = 6
//输出: 0 
//
// 
//
// 提示： 
//
// 
// 0 <= nums.length <= 10⁵ 
// -10⁹ <= nums[i] <= 10⁹ 
// nums 是一个非递减数组 
// -10⁹ <= target <= 10⁹ 
// 
//
// 
//
// 注意：本题与主站 34 题相同（仅返回值不同）：https://leetcode-cn.com/problems/find-first-and-last-
//position-of-element-in-sorted-array/ 
// Related Topics 数组 二分查找 👍 255 👎 0

package com.cute.leetcode.editor.cn;
public class ZaiPaiXuShuZuZhongChaZhaoShuZiLcof {
    public static void main(String[] args) {
        Solution solution = new ZaiPaiXuShuZuZhongChaZhaoShuZiLcof().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        /**
         * 排序数组，找一个数出现的次数
         * 找到第一个出现的位置以及最后一次出现的位置，然后做差
         * 查找位置时使用的二分查找
         */
        public int search(int[] nums, int target) {
            if (nums.length == 0) return 0;
            int left = 0;
            int right = nums.length - 1;
            int leftIndex, rightIndex, mid;
            while (left < right){
                mid = left + (right - left) / 2;// 左取整
                if (nums[mid] < target) left = mid + 1;
                else right = mid;
            }
            leftIndex = left;
            right = nums.length - 1;
            while (left < right){
                mid = left + (right - left) / 2 + 1;// 右取整
                if (nums[mid] > target) right = mid - 1;
                else left = mid;
            }
            rightIndex = left;
            return nums[rightIndex] == target && nums[leftIndex] == target ? rightIndex - leftIndex + 1 : 0;// 判断一下是否存在
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}